package com.reactim.user.service.impl;

import com.reactim.user.entity.UserPrivacySetting;
import com.reactim.user.repository.UserPrivacySettingRepository;
import com.reactim.user.repository.UserFriendRepository;
import com.reactim.user.service.UserPrivacyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 用户隐私设置服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserPrivacyServiceImpl implements UserPrivacyService {
    
    private final UserPrivacySettingRepository privacySettingRepository;
    private final UserFriendRepository userFriendRepository;
    
    @Override
    public UserPrivacySetting getUserPrivacySetting(Long userId) {
        return privacySettingRepository.findByUserId(userId)
                .orElseGet(() -> createDefaultPrivacySetting(userId));
    }
    
    @Override
    @Transactional
    public UserPrivacySetting updatePrivacySetting(Long userId, UserPrivacySetting setting) {
        UserPrivacySetting existingSetting = getUserPrivacySetting(userId);
        
        // 更新设置
        if (setting.getFriendRequestPermission() != null) {
            existingSetting.setFriendRequestPermission(setting.getFriendRequestPermission());
        }
        if (setting.getRequireVerification() != null) {
            existingSetting.setRequireVerification(setting.getRequireVerification());
        }
        if (setting.getAllowSearchByPhone() != null) {
            existingSetting.setAllowSearchByPhone(setting.getAllowSearchByPhone());
        }
        if (setting.getAllowSearchByEmail() != null) {
            existingSetting.setAllowSearchByEmail(setting.getAllowSearchByEmail());
        }
        if (setting.getAllowSearchByUsername() != null) {
            existingSetting.setAllowSearchByUsername(setting.getAllowSearchByUsername());
        }
        if (setting.getShowOnlineStatus() != null) {
            existingSetting.setShowOnlineStatus(setting.getShowOnlineStatus());
        }
        if (setting.getAllowGroupInvite() != null) {
            existingSetting.setAllowGroupInvite(setting.getAllowGroupInvite());
        }
        
        UserPrivacySetting updatedSetting = privacySettingRepository.save(existingSetting);
        
        log.info("更新用户隐私设置: userId={}", userId);
        
        return updatedSetting;
    }
    
    @Override
    @Transactional
    public UserPrivacySetting resetToDefault(Long userId) {
        // 删除现有设置
        privacySettingRepository.deleteByUserId(userId);
        
        // 创建默认设置
        UserPrivacySetting defaultSetting = createDefaultPrivacySetting(userId);
        
        log.info("重置用户隐私设置为默认: userId={}", userId);
        
        return defaultSetting;
    }
    
    @Override
    public boolean canBeSearched(Long userId, String searchType, String searchValue) {
        UserPrivacySetting setting = getUserPrivacySetting(userId);
        
        switch (searchType.toLowerCase()) {
            case "phone":
                return setting.getAllowSearchByPhone();
            case "email":
                return setting.getAllowSearchByEmail();
            case "username":
                return setting.getAllowSearchByUsername();
            default:
                return false;
        }
    }
    
    @Override
    public boolean canReceiveFriendRequest(Long fromUserId, Long toUserId) {
        UserPrivacySetting setting = getUserPrivacySetting(toUserId);
        
        switch (setting.getFriendRequestPermission()) {
            case NOBODY:
                return false;
            case CONTACTS_ONLY:
                // TODO: 实现联系人检查逻辑
                return false;
            case FRIENDS_OF_FRIENDS:
                return checkFriendsOfFriends(fromUserId, toUserId);
            case EVERYONE:
            default:
                return true;
        }
    }
    
    @Override
    public boolean shouldShowOnlineStatus(Long userId) {
        UserPrivacySetting setting = getUserPrivacySetting(userId);
        return setting.getShowOnlineStatus();
    }
    
    @Override
    public boolean allowGroupInvite(Long userId) {
        UserPrivacySetting setting = getUserPrivacySetting(userId);
        return setting.getAllowGroupInvite();
    }
    
    /**
     * 创建默认隐私设置
     */
    @Transactional
    protected UserPrivacySetting createDefaultPrivacySetting(Long userId) {
        UserPrivacySetting setting = new UserPrivacySetting();
        setting.setUserId(userId);
        setting.setFriendRequestPermission(UserPrivacySetting.FriendRequestPermission.EVERYONE);
        setting.setRequireVerification(true);
        setting.setAllowSearchByPhone(true);
        setting.setAllowSearchByEmail(true);
        setting.setAllowSearchByUsername(true);
        setting.setShowOnlineStatus(true);
        setting.setAllowGroupInvite(true);
        
        return privacySettingRepository.save(setting);
    }
    
    /**
     * 检查是否为朋友的朋友
     */
    private boolean checkFriendsOfFriends(Long fromUserId, Long toUserId) {
        // 获取fromUserId的所有好友
        // 检查这些好友中是否有人也是toUserId的好友
        // 这里需要复杂的查询，简化实现
        return userFriendRepository.existsMutualFriends(fromUserId, toUserId);
    }
}